﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nop.Core.Log;
using System.Web.Http.Filters;
using System.Web.Http.ExceptionHandling;
using System.Net.Http;
using System.Net;
namespace Spotshub.Api.Filter
{
    public class ExceptionHandlerAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            ILog _logService = LogManager.GetInstance().GetILog();
            var url = context.Request.RequestUri.ToString();
            var method = context.Request.Method.ToString();
            var Headers = context.Request.Content.Headers;
            if (Headers != null)
            {
                var strHead = new StringBuilder();
                strHead.Append("Url:" + url + ";");
                strHead.Append("Method:" + method + ";");
                foreach (var oneheader in Headers)
                {
                    var key = oneheader.Key;
                    var value = "";
                    if (oneheader.Value != null)
                    {
                        foreach (var oneHeardValue in oneheader.Value)
                        {
                            value = value + oneHeardValue.ToString();
                        }
                    }
                    strHead.Append(key + ":" + value + ";");
                }

                var stream = context.Request.Content.ReadAsStreamAsync().Result;
                stream.Position = 0;
                var reader = new StreamReader(stream);
                var content = reader.ReadToEnd();
                stream.Position = 0;
                strHead.Append("errorMessageExcetpion:" + context.Exception.Message);
                strHead.Append(";errorMessageStackTrace:" + context.Exception.StackTrace);
                strHead.Append(";UserWrite:" + content);
                _logService.Error(strHead.ToString());
            }
        }
    }
}
